package cn.legend.travel.admin.authorize.service.impl;

import cn.legend.travel.admin.authorize.dao.persist.repository.IFrontendMenuRepository;
import cn.legend.travel.admin.authorize.dao.persist.repository.IUserRepository;
import cn.legend.travel.admin.authorize.pojo.entity.User;
import cn.legend.travel.admin.authorize.pojo.vo.FrontendSubVO;
import cn.legend.travel.admin.authorize.pojo.vo.FrontendVO;
import cn.legend.travel.admin.authorize.service.IFrontendMenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class FrontendMenuServiceImpl implements IFrontendMenuService {
    private final IFrontendMenuRepository menuRepository;
    private final IUserRepository userRepository;

    /**
     * 对于从数据库取出来的所有菜单项，使用流先分组，然后再使用流转化出父级菜单组及设置子菜单组
     *
     * @param id 用户id
     * @return 返回一个双层级的菜单，即父级子级
     */
    @Override
    public List<FrontendVO> getMenuByRoleId(Long id) {
        User user = userRepository.getById(id);
        List<FrontendSubVO> menus = menuRepository.getMenuByRoleId(user.getRoleId());
        Map<Long, List<FrontendSubVO>> groupedMenus = menus.stream().collect(Collectors.groupingBy(FrontendSubVO::getPid));
        return groupedMenus.get(0L).stream().map(frontendSubVO -> {
            FrontendVO frontendVO = new FrontendVO();
            frontendVO.setId(frontendSubVO.getId());
            frontendVO.setName(frontendSubVO.getName());
            frontendVO.setSubmenu(groupedMenus.get(frontendVO.getId()));
            return frontendVO;
        }).collect(Collectors.toList());
    }
}
